package com.training.hatton.dropboxclient.processor;

import java.util.List;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.ResultReceiver;

import com.training.hatton.base.RequestDataWrapper;
import com.training.hatton.dropboxclient.ContextHolder;
import com.training.hatton.dropboxclient.content.Metadata;
import com.training.hatton.dropboxclient.content.contract.MetadataContract;
import com.training.hatton.dropboxclient.http.HttpManager;
import com.training.hatton.dropboxclient.processor.common.DropboxListModelProcessor;
import com.training.hatton.dropboxclient.service.ServiceHelper;
import com.training.hatton.dropboxclient.utill.DropboxService;

public class DeleteFileProcessor extends DropboxListModelProcessor<Metadata> {
	

	public DeleteFileProcessor(RequestDataWrapper dataWrapper, ResultReceiver resultReceiver) {
		super(dataWrapper, resultReceiver);
	}

	@Override
	public void executeProcess(HttpRequestBase request) throws Exception {
			sign(request);
			String source = HttpManager.get(ContextHolder.getInstance().getContext()).performAsString(request);
			List<Metadata> list = toListModel(source);
			if(list == null || list.isEmpty()){
				return;
			}
			Metadata md = list.remove(0);
			if(md.isDeleted()){
				ContextHolder.getInstance().getContext().getContentResolver().delete(MetadataContract.MetadataColumns.CONTENT_URI, MetadataContract.MetadataColumns.PATH + " = ? ", new String[]{md.getPath()});
				Bundle resultData = new Bundle();
				resultData.putBundle(ServiceHelper.EXTRA_DATA_REQUEST, getRequestData().getData());
				resultData.putString(DropboxService.EXTRA_ACTION, DropboxService.ACTION_DELETE);
				sendData(SUCCESS_CODE, resultData);
			}
	}
	
	@Override
	public Metadata createModel(JSONObject jsonObject) {
		return new Metadata(jsonObject);
	}

	@Override
	public HttpRequestBase buildHttpRequest(String url) {
    	HttpPost request = new HttpPost(url);
		return request;
	}
}
